<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>HTTP服务器API测试页面</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            max-width: 800px;
            margin: 50px auto;
            padding: 20px;
            background-color: #f5f5f5;
        }
        .container {
            background: white;
            padding: 30px;
            border-radius: 10px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }
        h1 {
            color: #333;
            text-align: center;
        }
        .form-group {
            margin-bottom: 20px;
        }
        label {
            display: block;
            margin-bottom: 5px;
            font-weight: bold;
            color: #555;
        }
        input[type="text"], input[type="datetime-local"] {
            width: 100%;
            padding: 10px;
            border: 1px solid #ddd;
            border-radius: 5px;
            font-size: 16px;
        }
        button {
            background-color: #007bff;
            color: white;
            padding: 12px 24px;
            border: none;
            border-radius: 5px;
            cursor: pointer;
            font-size: 16px;
            margin-right: 10px;
        }
        button:hover {
            background-color: #0056b3;
        }
        .btn-secondary {
            background-color: #6c757d;
        }
        .btn-secondary:hover {
            background-color: #545b62;
        }
        .result {
            margin-top: 20px;
            padding: 15px;
            border-radius: 5px;
            min-height: 50px;
        }
        .success {
            background-color: #d4edda;
            border-left: 4px solid #28a745;
            color: #155724;
        }
        .error {
            background-color: #f8d7da;
            border-left: 4px solid #dc3545;
            color: #721c24;
        }
        .info {
            background-color: #d1ecf1;
            border-left: 4px solid #17a2b8;
            color: #0c5460;
        }
        pre {
            background: #f8f9fa;
            padding: 10px;
            border-radius: 3px;
            overflow-x: auto;
        }
    </style>
</head>
<body>
    <div class="container">
        <h1>HTTP服务器API测试</h1>
        
        <!-- 设置系统时间 -->
        <div class="form-group">
            <h3>设置系统时间</h3>
            <label for="datetime">选择时间：</label>
            <input type="datetime-local" id="datetime" name="datetime">
            <br><br>
            <button onclick="setTime()">设置系统时间 (POST)</button>
            <button onclick="setTimeGet()" class="btn-secondary">设置系统时间 (GET)</button>
            <button onclick="getCurrentTime()" class="btn-secondary">获取当前时间 (GET)</button>
        </div>

        <!-- 获取TF卡信息 -->
        <div class="form-group">
            <h3>TF卡信息查询（GET请求）</h3>
            <label for="tfPath">TF卡挂载路径：</label>
            <input type="text" id="tfPath" name="tfPath" value="/mnt" placeholder="例如: /mnt/tf_card">
            <br><br>
            <button onclick="getTfInfo()">获取TF卡信息</button>
        </div>

        <!-- 服务器配置 -->
        <div class="form-group">
            <h3>服务器配置（POST请求）</h3>
            <label for="port">端口:</label>
            <input type="text" id="port" name="port" value="8080" placeholder="8080">
            <br><br>
            <label for="docRoot">文档根目录:</label>
            <input type="text" id="docRoot" name="docRoot" value="." placeholder=".">
            <br><br>
            <label for="maxConn">最大连接数:</label>
            <input type="text" id="maxConn" name="maxConn" value="10" placeholder="10">
            <br><br>
            <button onclick="setConfig()">设置服务器配置</button>
            <button onclick="getConfig()" class="btn-secondary">获取当前配置</button>
        </div>

        <!-- 其他测试功能 -->
        <div class="form-group">
            <h3>其他测试功能</h3>
            <button onclick="pingTest()" class="btn-secondary">Ping测试 (GET)</button>
            <button onclick="echoTest()" class="btn-secondary">Echo测试 (GET)</button>
            <button onclick="getVersion()" class="btn-secondary">获取版本信息 (GET)</button>
        </div>

        <!-- 结果显示区域 -->
        <div id="result" class="result" style="display: none;"></div>
    </div>

    <script>
        const serverUrl = 'http://localhost:8080';

        // 设置当前时间为默认值
        function setCurrentDateTime() {
            const now = new Date();
            const year = now.getFullYear();
            const month = String(now.getMonth() + 1).padStart(2, '0');
            const day = String(now.getDate()).padStart(2, '0');
            const hours = String(now.getHours()).padStart(2, '0');
            const minutes = String(now.getMinutes()).padStart(2, '0');
            
            const datetime = `${year}-${month}-${day}T${hours}:${minutes}`;
            document.getElementById('datetime').value = datetime;
        }

        // 页面加载时设置当前时间
        window.onload = function() {
            setCurrentDateTime();
        };

        // 显示结果
        function showResult(message, type = 'info') {
            const resultDiv = document.getElementById('result');
            resultDiv.className = `result ${type}`;
            resultDiv.innerHTML = message;
            resultDiv.style.display = 'block';
        }

        // 设置系统时间 (POST方式)
        async function setTime() {
            const datetime = document.getElementById('datetime').value;
            if (!datetime) {
                showResult('请选择时间', 'error');
                return;
            }

            // 转换为所需格式 YYYY-MM-DD HH:MM:SS (确保使用正确的分隔符)
            const timeStr = datetime.replace('T', ' ') + ':00';
            
            try {
                showResult('正在设置系统时间 (POST方式)...', 'info');
                
                const response = await fetch(`${serverUrl}/cgi/set_time`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/x-www-form-urlencoded',
                    },
                    body: `time=${encodeURIComponent(timeStr)}`
                });
                
                const result = await response.json();
                
                if (result.success) {
                    showResult(`✅ 系统时间设置成功！(POST)<br><strong>设置时间：</strong> ${result.time}<br><pre>${JSON.stringify(result, null, 2)}</pre>`, 'success');
                } else {
                    showResult(`❌ POST设置失败：${result.error}<br><pre>${JSON.stringify(result, null, 2)}</pre>`, 'error');
                }
            } catch (error) {
                showResult(`❌ POST请求失败：${error.message}`, 'error');
            }
        }

        // 设置系统时间 (GET方式)
        async function setTimeGet() {
            const datetime = document.getElementById('datetime').value;
            if (!datetime) {
                showResult('请选择时间', 'error');
                return;
            }

            // 转换为所需格式 YYYY-MM-DD HH:MM:SS
            const timeStr = datetime.replace('T', ' ') + ':00';
            
            try {
                showResult('正在设置系统时间 (GET方式)...', 'info');
                
                const response = await fetch(`${serverUrl}/cgi/set_time?time=${encodeURIComponent(timeStr)}`);
                const result = await response.json();
                
                if (result.success) {
                    showResult(`✅ 系统时间设置成功！(GET)<br><strong>设置时间：</strong> ${result.time}<br><pre>${JSON.stringify(result, null, 2)}</pre>`, 'success');
                } else {
                    showResult(`❌ GET设置失败：${result.error}<br><pre>${JSON.stringify(result, null, 2)}</pre>`, 'error');
                }
            } catch (error) {
                showResult(`❌ GET请求失败：${error.message}`, 'error');
            }
        }

        // 获取当前时间
        async function getCurrentTime() {
            try {
                showResult('正在获取服务器时间...', 'info');
                
                const response = await fetch(`${serverUrl}/cgi/get_time`);
                const result = await response.json();
                
                showResult(`📅 服务器当前时间：<strong>${result.time}</strong><br><pre>${JSON.stringify(result, null, 2)}</pre>`, 'success');
            } catch (error) {
                showResult(`❌ 获取时间失败：${error.message}`, 'error');
            }
        }

        // 获取TF卡信息
        async function getTfInfo() {
            const path = document.getElementById('tfPath').value || '/mnt';
            
            try {
                showResult('正在获取TF卡信息...', 'info');
                
                const response = await fetch(`${serverUrl}/cgi/get_tf_info?path=${encodeURIComponent(path)}`);
                const result = await response.json();
                
                if (result.success) {
                    showResult(`💾 TF卡信息：<br>
                        <strong>挂载路径：</strong> ${result.mount_path}<br>
                        <strong>总容量：</strong> ${result.total_formatted}<br>
                        <strong>剩余容量：</strong> ${result.free_formatted}<br>
                        <strong>已使用：</strong> ${result.used_formatted}<br>
                        <strong>使用率：</strong> ${result.usage_percent.toFixed(2)}%<br>
                        <pre>${JSON.stringify(result, null, 2)}</pre>`, 'success');
                } else {
                    showResult(`❌ 获取TF卡信息失败：${result.error}<br><pre>${JSON.stringify(result, null, 2)}</pre>`, 'error');
                }
            } catch (error) {
                showResult(`❌ 请求失败：${error.message}`, 'error');
            }
        }

        // 设置服务器配置
        async function setConfig() {
            const port = document.getElementById('port').value;
            const docRoot = document.getElementById('docRoot').value;
            const maxConn = document.getElementById('maxConn').value;
            
            const params = new URLSearchParams();
            if (port) params.append('port', port);
            if (docRoot) params.append('document_root', docRoot);
            if (maxConn) params.append('max_connections', maxConn);
            
            try {
                showResult('正在设置服务器配置...', 'info');
                
                const response = await fetch(`${serverUrl}/cgi/set_config`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/x-www-form-urlencoded',
                    },
                    body: params.toString()
                });
                
                const result = await response.json();
                
                if (result.success) {
                    showResult(`⚙️ 服务器配置更新成功！<br>
                        <strong>端口：</strong> ${result.config.port}<br>
                        <strong>文档根目录：</strong> ${result.config.document_root}<br>
                        <strong>最大连接数：</strong> ${result.config.max_connections}<br>
                        <pre>${JSON.stringify(result, null, 2)}</pre>`, 'success');
                } else {
                    showResult(`❌ 配置设置失败<br><pre>${JSON.stringify(result, null, 2)}</pre>`, 'error');
                }
            } catch (error) {
                showResult(`❌ 请求失败：${error.message}`, 'error');
            }
        }

        // 获取服务器配置
        async function getConfig() {
            try {
                showResult('正在获取服务器配置...', 'info');
                
                const response = await fetch(`${serverUrl}/config`);
                const result = await response.json();
                
                showResult(`⚙️ 当前服务器配置：<br>
                    <strong>端口：</strong> ${result.port}<br>
                    <strong>文档根目录：</strong> ${result.document_root}<br>
                    <strong>最大连接数：</strong> ${result.max_connections}<br>
                    <pre>${JSON.stringify(result, null, 2)}</pre>`, 'success');
            } catch (error) {
                showResult(`❌ 获取配置失败：${error.message}`, 'error');
            }
        }

        // Ping测试
        async function pingTest() {
            try {
                showResult('正在执行Ping测试...', 'info');
                
                const response = await fetch(`${serverUrl}/cgi/ping`);
                const result = await response.json();
                
                showResult(`🏓 Ping测试结果：<br>
                    <strong>响应：</strong> ${result.response}<br>
                    <strong>计数：</strong> ${result.count || 'N/A'}<br>
                    <pre>${JSON.stringify(result, null, 2)}</pre>`, 'success');
            } catch (error) {
                showResult(`❌ Ping测试失败：${error.message}`, 'error');
            }
        }

        // Echo测试
        async function echoTest() {
            try {
                showResult('正在执行Echo测试...', 'info');
                
                const testParams = 'param1=hello&param2=world&param3=test';
                const response = await fetch(`${serverUrl}/cgi/echo?${testParams}`);
                const result = await response.json();
                
                showResult(`🔊 Echo测试结果：<br>
                    <strong>参数回显：</strong><br>
                    ${JSON.stringify(result.echo, null, 2).replace(/[{}"]/g, '').replace(/,/g, '<br>')}<br>
                    <pre>${JSON.stringify(result, null, 2)}</pre>`, 'success');
            } catch (error) {
                showResult(`❌ Echo测试失败：${error.message}`, 'error');
            }
        }

        // 获取版本信息
        async function getVersion() {
            try {
                showResult('正在获取版本信息...', 'info');
                
                const response = await fetch(`${serverUrl}/version`);
                const result = await response.json();
                
                showResult(`💻 服务器版本信息：<br>
                    <strong>版本：</strong> ${result.version}<br>
                    <pre>${JSON.stringify(result, null, 2)}</pre>`, 'success');
            } catch (error) {
                showResult(`❌ 获取版本信息失败：${error.message}`, 'error');
            }
        }
    </script>
</body>
</html>